<template>
  <el-dialog
    v-model="state.visible"
    :title="state.title"
    width="900px"
    draggable
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="detail-content" v-loading="state.loading">
      <!-- 申请基本信息 -->
      <el-card shadow="never" class="mb-4">
        <template #header>
          <div class="card-header">
            <span class="header-title">申请基本信息</span>
            <div class="header-tags">
              <el-tag :type="state.data?.flowType === '入库' ? 'success' : 'warning'">
                {{ state.data?.flowType }}申请
              </el-tag>
              <el-tag :type="getStatusTagType(state.data?.approvalAction)" class="ml-2">
                {{ getStatusText(state.data?.approvalAction) }}
              </el-tag>
            </div>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="申请号">
            <el-text class="font-weight-500">{{ state.data?.requestNo }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="申请批次">{{ state.data?.batchNo }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ state.data?.requestTime }}</el-descriptions-item>
          <el-descriptions-item label="物资分类">{{ state.data?.storeTypeDisplayName }}</el-descriptions-item>
          <el-descriptions-item label="物资名称">
            <el-text class="font-weight-500">{{ state.data?.materialName }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="预期时间">{{ state.data?.expectedDate }}</el-descriptions-item>
          <el-descriptions-item label="申请数量" span="2">
            <el-tag type="info" size="large">
              {{ state.data?.quantity }} {{ state.data?.unit }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="物资单价">
            <el-text class="price-text">¥{{ state.data?.materialPrice }}</el-text>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 人员信息 -->
      <el-card shadow="never" class="mb-4">
        <template #header>
          <div class="card-header">
            <span class="header-title">人员信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请人">
            <div class="person-info">
              <el-text class="person-name">{{ state.data?.applicantName }}</el-text>
              <el-text type="info" size="small">{{ state.data?.applicantDept }}</el-text>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="接收人">
            <div class="person-info">
              <el-text class="person-name">{{ state.data?.receiverName }}</el-text>
              <el-text type="info" size="small">{{ state.data?.receiverDept }}</el-text>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="确认人" span="2">
            <div class="person-info" v-if="state.data?.confirmerName">
              <el-text class="person-name">{{ state.data?.confirmerName }}</el-text>
            </div>
            <el-text type="info" v-else>未指定</el-text>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 审批流程进度 -->
      <el-card shadow="never" class="mb-4">
        <template #header>
          <div class="card-header">
            <span class="header-title">审批流程进度</span>
            <el-tag :type="state.data?.currentStep === state.data?.totalSteps ? 'success' : 'warning'" size="small">
              步骤 {{ state.data?.currentStep }} / {{ state.data?.totalSteps }}
            </el-tag>
          </div>
        </template>
        <div class="flow-steps">
          <div class="custom-steps">
            <div 
              v-for="(step, index) in flowSteps" 
              :key="index"
              class="step-item"
              :class="getStepClass(index + 1)"
            >
              <div class="step-content">
                <div class="step-icon">
                  <span v-if="getStepStatus(index + 1) === 'finish'" class="step-check">✓</span>
                  <span v-else-if="getStepStatus(index + 1) === 'error'" class="step-error">✗</span>
                  <span v-else class="step-number">{{ index + 1 }}</span>
                </div>
                <div class="step-info">
                  <div class="step-title">{{ step.title }}</div>
                  <div class="step-description">{{ step.description }}</div>
                </div>
              </div>
              <div 
                v-if="index < flowSteps.length - 1" 
                class="step-connector"
                :class="{ 'connector-active': getStepStatus(index + 2) === 'finish' || getStepStatus(index + 2) === 'process' }"
              ></div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 审批历史 -->
      <el-card shadow="never" v-if="state.data?.approvalAction !== 1">
        <template #header>
          <div class="card-header">
            <span class="header-title">审批历史</span>
          </div>
        </template>
        <div class="approval-history">
          <div class="history-item" v-if="state.data?.firstApprovalTime">
            <div class="history-header">
              <el-tag :type="getStatusTagType(state.data?.firstApprovalStatus)" size="small">
                {{ getStatusText(state.data?.firstApprovalStatus) }}
              </el-tag>
              <el-text type="primary" class="history-person">{{ state.data?.firstApproverName }}</el-text>
              <el-text type="info" class="history-time">{{ state.data?.firstApprovalTime }}</el-text>
            </div>
          </div>
          <div class="history-item" v-if="state.data?.secondApprovalTime">
            <div class="history-header">
              <el-tag :type="getStatusTagType(state.data?.secondApprovalStatus)" size="small">
                {{ getStatusText(state.data?.secondApprovalStatus) }}
              </el-tag>
              <el-text type="primary" class="history-person">{{ state.data?.secondApproverName }}</el-text>
              <el-text type="info" class="history-time">{{ state.data?.secondApprovalTime }}</el-text>
            </div>
          </div>
          <div class="history-item" v-if="state.data?.finalExecutionTime">
            <div class="history-header">
              <el-tag type="success" size="small">已执行</el-tag>
              <el-text type="primary" class="history-person">{{ state.data?.finalExecutorName }}</el-text>
              <el-text type="info" class="history-time">{{ state.data?.finalExecutionTime }}</el-text>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 备注信息 -->
      <el-card shadow="never" v-if="state.data?.remark">
        <template #header>
          <div class="card-header">
            <span class="header-title">备注信息</span>
          </div>
        </template>
        <el-text class="remark-content">{{ state.data?.remark }}</el-text>
      </el-card>
    </div>

    <template #footer>
      <div class="detail-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { useStoreProcessFlowStepApi } from '/@/api/store/storeProcessFlowStep';

const storeProcessFlowStepApi = useStoreProcessFlowStepApi();

const state = reactive({
  visible: false,
  loading: false,
  title: '',
  data: null as any,
});

// 流程步骤定义
const flowSteps = computed(() => {
  if (!state.data) return [];
  
  const isInbound = state.data.flowType === '入库';
  const isOutbound = state.data.flowType === '出库';
  
  if (isInbound) {
    return [
      { title: '已申请', description: '申请人提交入库申请' },
      { title: '待审核', description: '部门主管审核' },
      { title: '待审批', description: '部门物资负责人审批' },
      { title: '待发放', description: '发放入库操作' },
      { title: '已完成', description: '入库操作完成' }
    ];
  } else if (isOutbound) {
    return [
      { title: '已申请', description: '申请人提交出库申请' },
      { title: '待审核', description: '区域主管审核' },
      { title: '待审批', description: '部门主管审批' },
      { title: '待发放', description: '发放出库操作' },
      { title: '已完成', description: '出库操作完成' }
    ];
  }
  
  return [];
});

// 获取步骤状态
const getStepStatus = (stepNumber: number) => {
  if (!state.data) return 'wait';
  
  const approvalAction = state.data.approvalAction;
  const isInbound = state.data.flowType === '入库';
  const isOutbound = state.data.flowType === '出库';

  // 申请步骤(第1步)永远是完成状态
  if (stepNumber === 1) {
    return 'finish';
  }
  
  
  // 根据approvalAction状态映射到具体步骤和拒绝位置
  // 现在的步骤是：申(1)-核(2)-批(3)-放(4)-完(5)
  let completedStep = 1; // 申请永远完成
  let activeStep = 2; // 默认审核中
  let rejectStep = 0; // 拒绝发生的步骤
  
  switch (approvalAction) {
    case 1: // 待审核 - 第2步进行中
      completedStep = 1;
      activeStep = 2;
      break;
    case 2: // 已审核 - 第2步完成，第3步进行中
      completedStep = 2;
      activeStep = 3;
      break;
    case 3: // 已审批 - 第3步完成，第4步进行中
      completedStep = 3;
      activeStep = 4;
      break;
    case 4: // 已完成/已发放 - 全部完成
      completedStep = 5;
      activeStep = 5;
      break;
    case 5: // 已拒绝 - 根据processSteps数据判断拒绝位置
      // 如果有processSteps数据，使用更准确的步骤信息
      if (state.data.processSteps && Array.isArray(state.data.processSteps)) {
        // 找到拒绝步骤（status为5的步骤）
        const rejectStepData = state.data.processSteps.find(step => step.status === 5);
        if (rejectStepData) {
          // 找到拒绝之前最后一个正常步骤
          let lastCompletedStatus = 1; // 申请总是完成的
          for (const step of state.data.processSteps) {
            if (step.status === 5) break; // 遇到拒绝就停止
            if (step.status > lastCompletedStatus && step.status !== 5) {
              lastCompletedStatus = step.status;
            }
          }
          
          // 根据最后完成的状态映射到UI步骤
          // processSteps的status: 1=申请, 2=审核, 3=审批, 4=发放
          // UI步骤: 1=申请, 2=审核, 3=审批, 4=发放, 5=完成
          const statusToStepMap = { 1: 1, 2: 2, 3: 3, 4: 4 };
          completedStep = statusToStepMap[lastCompletedStatus] || 1;
          
          // 拒绝发生在最后一个完成步骤的下一步
          if (lastCompletedStatus === 3) {
            // 如果审批已完成，拒绝发生在发放环节
            rejectedAtStep = 4;
          } else if (lastCompletedStatus === 2) {
            // 如果审核已完成，拒绝发生在审批环节  
            rejectedAtStep = 3;
          } else {
            // 如果只有申请完成，拒绝发生在审核环节
            rejectedAtStep = 2;
          }
        } else {
          // 没有找到拒绝步骤，默认处理
          rejectedAtStep = 2;
          completedStep = 1;
        }
      } else {
        // 没有processSteps数据，使用原来的逻辑
        let rejectedAtStep = 2; // 默认第2步（审核）
        
        if (isInbound) {
          // 入库流程：申请->部门主管审核->部门物资负责人审批->发放->完成
          if (state.data.firstApprovalTime && state.data.firstApprovalStatus === 2) {
            rejectedAtStep = 2;
            completedStep = 1;
          } else if (state.data.secondApprovalTime && state.data.secondApprovalStatus === 2) {
            rejectedAtStep = 3;
            completedStep = 2;
          } else if (state.data.finalExecutionTime && state.data.finalExecutionStatus === 2) {
            rejectedAtStep = 4;
            completedStep = 3;
          }
        } else if (isOutbound) {
          // 出库流程：申请->区域主管审核->部门主管审批->发放->完成
          if (state.data.firstApprovalTime && state.data.firstApprovalStatus === 2) {
            rejectedAtStep = 2;
            completedStep = 1;
          } else if (state.data.secondApprovalTime && state.data.secondApprovalStatus === 2) {
            rejectedAtStep = 3;
            completedStep = 2;
          } else if (state.data.finalExecutionTime && state.data.finalExecutionStatus === 2) {
            rejectedAtStep = 4;
            completedStep = 3;
          }
        }
      }
      
      rejectStep = rejectedAtStep;
      break;
    default:
      completedStep = 1;
      activeStep = 2;
  }
  
  // 处理拒绝状态
  if (approvalAction === 5) {
    if (stepNumber <= completedStep) {
      return 'finish'; // 之前的步骤都完成了
    } else if (stepNumber === rejectStep) {
      return 'error'; // 当前步骤被拒绝
    } else {
      return 'wait'; // 后续步骤等待
    }
  }
  
  // 处理正常状态
  if (stepNumber <= completedStep) {
    return 'finish';
  } else if (stepNumber === activeStep) {
    return 'process';
  } else {
    return 'wait';
  }
};

// 获取步骤样式类
const getStepClass = (stepNumber: number) => {
  const status = getStepStatus(stepNumber);
  return `step-${status}`;
};


// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch(status) {
    case 1: return 'info';     // 待审核
    case 2: return 'warning';  // 已审核
    case 3: return 'success';  // 已审批
    case 4: return 'success';  // 已完成
    case 5: return 'danger';   // 已拒绝
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch(status) {
    case 1: return '待审核';
    case 2: return '已审核';
    case 3: return '已审批';
    case 4: return '已完成';
    case 5: return '已拒绝';
    default: return '未知';
  }
};

// 打开详情弹窗
const openDialog = async (row: any) => {
  state.title = `审批详情 - ${row.requestNo}`;
  state.loading = true;
  state.visible = true;
  
  try {
    // 获取详细数据
    const result = await storeProcessFlowStepApi.detail(row.id);
    state.data = result.data.result;
  } catch (error) {
    console.error('获取审批详情失败:', error);
    // 如果获取失败，使用传入的行数据
    state.data = row;
  } finally {
    state.loading = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  state.visible = false;
  state.data = null;
};

// 暴露方法
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>
.detail-content {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-title {
      font-weight: 600;
      color: #303133;
    }
    
    .header-tags {
      display: flex;
      align-items: center;
      
      .ml-2 {
        margin-left: 8px;
      }
    }
  }
  
  .mb-4 {
    margin-bottom: 16px;
  }
  
  .font-weight-500 {
    font-weight: 500;
  }
  
  .price-text {
    color: #409eff;
    font-weight: 500;
  }
  
  .person-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    .person-name {
      font-weight: 500;
    }
  }
  
  .flow-steps {
    padding: 20px 0;
  }
  
  .custom-steps {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
  
  .step-item {
    display: flex;
    align-items: flex-start;
    position: relative;
  }
  
  .step-content {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    flex: 1;
  }
  
  .step-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 16px;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }
  
  .step-info {
    flex: 1;
    padding-top: 2px;
  }
  
  .step-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .step-description {
    font-size: 14px;
    color: #606266;
    margin-bottom: 4px;
  }
  
  
  .step-reject-info {
    margin-top: 6px;
    padding: 4px 8px;
    background-color: #fef0f0;
    border: 1px solid #fbc4c4;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .reject-label {
    color: #f56c6c;
    font-weight: 500;
  }
  
  .reject-name {
    color: #f56c6c;
    font-weight: 600;
  }
  
  .step-connector {
    position: absolute;
    left: 19px;
    top: 40px;
    width: 2px;
    height: 24px;
    background-color: #e4e7ed;
    transition: background-color 0.3s ease;
  }
  
  .connector-active {
    background-color: #67c23a;
  }
  
  /* 不同状态的样式 */
  .step-wait .step-icon {
    background-color: #f0f2f5;
    color: #909399;
    border: 2px solid #e4e7ed;
  }
  
  .step-process .step-icon {
    background-color: #409eff;
    color: #ffffff;
    border: 2px solid #409eff;
    animation: pulse 2s infinite;
  }
  
  .step-finish .step-icon {
    background-color: #67c23a;
    color: #ffffff;
    border: 2px solid #67c23a;
  }
  
  .step-error .step-icon {
    background-color: #f56c6c;
    color: #ffffff;
    border: 2px solid #f56c6c;
  }
  
  .step-finish .step-title,
  .step-process .step-title {
    color: #303133;
  }
  
  .step-wait .step-title {
    color: #909399;
  }
  
  .step-error .step-title {
    color: #f56c6c;
  }
  
  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
    }
    50% {
      box-shadow: 0 0 0 8px rgba(64, 158, 255, 0.1);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
    }
  }
  
  .approval-history {
    .history-item {
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .history-header {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .history-person {
          font-weight: 500;
        }
        
        .history-time {
          margin-left: auto;
        }
      }
    }
  }
  
  .remark-content {
    line-height: 1.6;
    color: #606266;
  }
}

.detail-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-card__header) {
  padding: 14px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-steps .el-step__title) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-steps .el-step__description) {
  font-size: 12px;
  color: #909399;
}
</style>